import logging

from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ocr_api20210707.client import Client as Client
from alibabacloud_ocr_api20210707 import models as models
from alibabacloud_tea_util import models as util_models
import  json

#阿里云的OCR识别
#密钥及 accessKey为思路迪账户


#控制台开通账号的 权限
# 您的AccessKey ID,
#LTAI5tCTgNodvGJQt6Dz8FJA
access_key_id = "LTAI5tCTgNodvGJQt6Dz8FJA"
# 您的AccessKey Secret,
#1A8u159ypUkJ6XiTuzu7stAEIGzrKr
access_key_secret = "1A8u159ypUkJ6XiTuzu7stAEIGzrKr"
# 访问的域名
endpoint = 'ocr-api.cn-hangzhou.aliyuncs.com'
#增值税API接口名称
api_name = models.RecognizeInvoiceRequest()

logger = logging.getLogger(__name__)

def aliyun_client():
    # 阿里云认证
    config = open_api_models.Config(
        # 您的AccessKey ID,
        access_key_id = access_key_id,
        # 您的AccessKey Secret,
        access_key_secret = access_key_secret
    )
    config.endpoint =  endpoint
    return   Client(config)

def aliyun_request_data(body):
    aliyun_request = api_name
    #装填需要OCR的图片
    aliyun_request.body = body

    runtime = util_models.RuntimeOptions()

    client = aliyun_client()
    #请求 这里需要写try 日志-------------------------------------
    try:
        response = client.recognize_invoice_with_options(aliyun_request,runtime)
        logger.error("发票识别成功")
    except Exception as e:
        logger.error("错误代码:" + e.Code)
        logger.error("错误信息:" + e.Message)
        raise e.Message
    #返回的数据转换成json
    json_data = json.loads(response.body.data)
    return  json_data['data']

